package com.team9.fitness.mapper;

import com.team9.fitness.entity.UserAvatar;
import org.apache.ibatis.annotations.*;

import java.util.List;

/**
 * 用户头像Mapper
 */
@Mapper
public interface UserAvatarMapper {

    /**
     * 插入用户头像
     */
    @Insert("INSERT INTO user_avatar (user_id, avatar_url, file_name, file_size, mime_type, upload_time, is_active, created_at, updated_at) " +
            "VALUES (#{userId}, #{avatarUrl}, #{fileName}, #{fileSize}, #{mimeType}, #{uploadTime}, #{isActive}, #{createdAt}, #{updatedAt})")
    @Options(useGeneratedKeys = true, keyProperty = "id")
    int insert(UserAvatar userAvatar);

    /**
     * 根据用户ID获取激活的头像
     */
    @Select("SELECT * FROM user_avatar WHERE user_id = #{userId} AND is_active = 1 ORDER BY upload_time DESC LIMIT 1")
    UserAvatar findByUserIdAndActive(@Param("userId") Long userId);

    /**
     * 根据用户ID获取所有头像
     */
    @Select("SELECT * FROM user_avatar WHERE user_id = #{userId} ORDER BY upload_time DESC")
    List<UserAvatar> findByUserId(@Param("userId") Long userId);

    /**
     * 更新头像激活状态
     */
    @Update("UPDATE user_avatar SET is_active = #{isActive}, updated_at = #{updatedAt} WHERE id = #{id}")
    int updateActiveStatus(@Param("id") Long id, @Param("isActive") Boolean isActive, @Param("updatedAt") java.time.LocalDateTime updatedAt);

    /**
     * 将用户的所有头像设为非激活
     */
    @Update("UPDATE user_avatar SET is_active = 0, updated_at = NOW() WHERE user_id = #{userId}")
    int deactivateAllByUserId(@Param("userId") Long userId);

    /**
     * 删除头像
     */
    @Delete("DELETE FROM user_avatar WHERE id = #{id}")
    int deleteById(@Param("id") Long id);

    /**
     * 根据用户ID删除所有头像
     */
    @Delete("DELETE FROM user_avatar WHERE user_id = #{userId}")
    int deleteByUserId(@Param("userId") Long userId);

    /**
     * 清理30天前的非激活头像
     */
    @Delete("DELETE FROM user_avatar WHERE is_active = 0 AND upload_time < DATE_SUB(NOW(), INTERVAL 30 DAY)")
    int cleanInactiveAvatars();
}
